package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    /**
     * 用户完善信息
     * @param userInfo
     */
    public void save(UserInfo userInfo){
        userInfoApi.save(userInfo);
    }


    /**
     * 用户上传/更新头像（业务层）
     * @param headPhoto
     * @param id
     */
    public void uploadUserHeadImage(MultipartFile headPhoto, Long id) throws IOException {
        //1.把照片上穿到阿里云oss，得到照片访问的URL路径
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2.调用百度人脸识别，检测照片中是否有人脸
        boolean result = aipFaceTemplate.checkFace(imageUrl);
        //3.用户上传的头像没有人脸，抛出异常
        if(!result){
            throw new BusinessException(ErrorResult.faceError());
        }else{
            //4，有人脸，调用api更新头像
          UserInfo userInfo = new UserInfo();
          userInfo.setId(Long.valueOf(id));
          userInfo.setAvatar(imageUrl);
          userInfoApi.update(userInfo);
        }
    }
}
